import React from 'react';
import { inject, observer} from 'mobx-react';
import * as mobx from 'mobx';
import {WeaTableNew} from 'comsMobx';
import { Button , Modal,message} from 'antd';
import {WeaTab,WeaRightMenu,WeaTools,WeaErrorPage,WeaLocaleProvider,WeaDialog,WeaFormItem,WeaSwitch,WeaSearchGroup} from 'ecCom';
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';

const { toJS } = mobx;
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;

@observer
class ImportModelDialog extends React.Component {
    constructor(props) {
		super(props);
    }
    doInit(props){}
    componentDidMount() {
        this.doInit(this.props);
    }
    componentWillReceiveProps(nextProps) {}
    render() {
        const { workflowNewDesignStore ,isFree=''} = this.props;
        const { setModelImportDialogShow , modelImportModelShow , importModelTableStore , importModelForm ,setImportModalAdShow ,
        importModalAdShow,searchExistedModelList,postImportModelDatas,wfFreeDatas} = workflowNewDesignStore;
        const AdFormParams = importModelForm.getFormParams(); 

        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@mk40fj`}
                visible={modelImportModelShow}
                title={getLabel(23039,'选择模板')}
                icon="icon-coms-workflow"
                iconBgcolor='#0079DE'
                maskClosable={false}
                buttons={this.getModalBtns()}
                onCancel={() => setModelImportDialogShow(false)}
                style={{width: "800px",height:'400px'}}
                moreBtn={{datas:this.getRightMenu()}}
                hasScroll
            >
                <div className="wf-free-flowset-importModal">
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@zm0kap`} 
                        collectParams={{favname:getLabel(23039,'选择模板'), favouritetype:2}}
                        datas={this.getRightMenu()}>
                        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@klhz11`}
                            buttonsAd={this.getListAdButtons()}
                            searchType={['base','advanced']}
                            advanceHeight = {75}
                            searchsBaseValue={AdFormParams.name}
                            setShowSearchAd={bool=>{setImportModalAdShow(bool)}}
                            hideSearchAd={()=> setImportModalAdShow(false)}
                            searchsAd={this.getCusAdvancedSearch()}
                            showSearchAd={importModalAdShow}
                            onSearch={v=>{searchExistedModelList()}}
                            onSearchChange={v=>{importModelForm.updateFields({name:{value:v}})}}
                        />
                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@3ksskm`} 
                            comsWeaTableStore={importModelTableStore}
                            hasOrder={true}
                            needRowClick={true}
                            scroll={{y: 265}}
                            /*
                            
                            onRowClick = {(record, index)=>{
                                const {id=''} = record;
                                if(isEmpty(toJS(wfFreeDatas))){
                                    postImportModelDatas({targetTemplateid:id,isFree});
                                }else{
                                    Modal.confirm({
                                        title: getLabel('131329', '信息确认'),
                                        content: `${isFree=='1' ? '导入模板将替换已设置的自由节点，是否继续？' : '导入模板将替换加签流转，是否继续？'}`,
                                        onOk: () => {
                                            postImportModelDatas({targetTemplateid:id,isFree});
                                        },
                                        okText: getLabel(83446,'确定'),
                                        okCancel : () => {},
                                    });
                                }
                                // postImportModelDatas({templateid:id,isFree});
                            }}
                            */
                        />
                    </WeaRightMenu>
                </div>
            </WeaDialog>
        )
    }
    getAdvancedSearch = () => {
        const { workflowNewDesignStore } = this.props;
        const { importModelForm } = workflowNewDesignStore;
        const coms = importModelForm.render({
            needTigger: false,
            showGroup:true,
            showTitle:false
            }, {
        });
        return coms;
    }
    getCusAdvancedSearch() {
        const { workflowNewDesignStore } = this.props;
        const { importModelForm, modelAdCondition } = workflowNewDesignStore;
        const {isFormInit} = importModelForm;
        let group = [];
        isFormInit && toJS(modelAdCondition).map((c,gindex) =>{
            let items = [];
            c.items.map(field => {
                const domKey = typeof field.domkey === "object" ? field.domkey[0] : field.domkey;
            let col = 2;
            if (field.conditionType.toUpperCase() == WeaTools.types.CASCADER) col = 1;
            items.push({
                com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@vp1q84@${domKey}`}
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    ratio1to2
                    error={importModelForm.getError(field)}
                    tipPosition="bottom"
                    wrapperCol={{span: `${field.fieldcol}`}}>
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@w9fs4o@${domKey}`} fieldConfig={field} form={importModelForm}/>
                    </WeaFormItem>),
                col:col,
                hide: importModelForm.isHide(field, (keys, allParams)=> {
                return false;
                })
            })
            });
            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@193nq4@${gindex}`} needTigger={false} showTitle = {false} showGroup={true} items={items}/>)
        });
        return group;
    }
    confirmSelection = () => {
        const { workflowNewDesignStore , isFree=''} = this.props;
        const { importModelTableStore , wfFreeDatas , postImportModelDatas,currentPostParams = {}} = workflowNewDesignStore;
        const selectedRowKeys = importModelTableStore.selectedRowKeys;
        if(isEmpty(toJS(selectedRowKeys))){
            message.warning(getLabel(506881,"请先选择模板"));
            return;
        }
        const {templateid = -1} = currentPostParams;
        let hasFreeNode = false;
        const tempFreeDatas = toJS(wfFreeDatas);
        if(templateid > 0) {
            if(!isEmpty(tempFreeDatas)) {
                let keys = Object.keys(tempFreeDatas);
                keys.map((key)=>{
                    let arr = tempFreeDatas[key];
                    if(arr.length > 0) {
                        let tempData = arr[0];
                        while (tempData.hasNext) {
                            if(!tempData.trunkNode) {
                                hasFreeNode = true;
                                break;
                            }
                            tempData = tempData.next;
                        }
                    }
                })
            }
        }

        //未设置过自由节点数据则直接导入
        if(isEmpty(toJS(wfFreeDatas)) || (templateid > 0 && !hasFreeNode)){
            postImportModelDatas({targetTemplateid:selectedRowKeys[0],isFree});
        }else{
            Modal.confirm({
                title: getLabel('131329', '信息确认'),
                content: `${isFree=='1' ? getLabel(506882,'导入模板将替换已设置的自由节点，是否继续？') : getLabel(506883,'导入模板将替换加签流转，是否继续？')}`,
                onOk: () => {
                    postImportModelDatas({targetTemplateid:selectedRowKeys[0],isFree});
                },
                okText: getLabel(83446,'确定'),
                okCancel : () => {},
            });
        }
    }
    getListAdButtons(){
        const { workflowNewDesignStore } = this.props;
        const {searchExistedModelList,setImportModalAdShow,importModelForm} = workflowNewDesignStore;
        return [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7yre2y@search`} type="primary" onClick={()=>{searchExistedModelList();setImportModalAdShow(false);}}>{getLabel(197,'搜索')}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gaipk6@reset`} type="ghost" onClick={()=>{importModelForm.resetConditionValue();}}>{getLabel(2022,'重置')}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9z82gs@cancel`} type="ghost" onClick={()=>{setImportModalAdShow(false)}}>{getLabel(31129,'取消')}</Button>)
        ];
    }
    getModalBtns(){
        const { workflowNewDesignStore } = this.props;
        const { setModelImportDialogShow ,loading = false} = workflowNewDesignStore;
        let btns = [];
        btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ps79ra@confirm`} type="primary" loading={loading} onClick={()=>{this.confirmSelection()}}>{getLabel(83446,'确定')}</Button>);
        btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p89qh3@cancel`} type="primary" loading={loading} onClick={()=>{setModelImportDialogShow(false)}}>{getLabel(201,'取消')}</Button>);
        return btns;
    }
    getRightMenu(){
        const { workflowNewDesignStore } = this.props;
        const { setModelImportDialogShow,loading = false } = workflowNewDesignStore;
        let rtMenus = [];
        rtMenus.push({
            key: "clear",
    		icon: <i className="icon-coms-complete"/>,
            disabled:loading,
            content:getLabel(83446,'确定'),
            onClick: key =>{this.confirmSelection()}
        });
        rtMenus.push({
            key: "cancel",
    		icon: <i className="icon-coms-Clear"/>,
            content:getLabel(201,'取消'),
            disabled:loading,
            onClick: key =>{setModelImportDialogShow(false)}
        });
    	return rtMenus;
    }
}

export default WeaTools.tryCatch(React, 
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@uoy99e`} msg={ props.error ? props.error : getLabel(383324,' 对不起，该页面异常，请联系管理员 ')+'！'} />,
    {error: ""}
)(ImportModelDialog);